<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
      <el-form-item :label="$t('basic.codeRule.ruleName')" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          :placeholder="$t('enterTip') + $t('basic.codeRule.ruleName')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item v-show="false" :label="$t('basic.codeRule.ruleName')" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          :placeholder="$t('enterTip') + $t('basic.codeRule.ruleName')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="规则状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('search')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('reset')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:codeRule:add']"
        >{{$t('add')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:codeRule:edit']"
        >{{$t('edit')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:codeRule:remove']"
        >{{$t('delete')}}</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:codeRule:export']"
        >{{$t('export')}}</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <af-table-column label="规则编号" align="center" prop="no" />
      <af-table-column label="规则名称" align="center" prop="ruleName" />
      <af-table-column label="规则类型" align="center" prop="ruleType" >
        <template slot-scope="scope">
          <dict-tag :options="ruleTypeList" :value="scope.row.ruleType"/>
        </template>
      </af-table-column>
      <el-table-column :label="$t('status')" align="center" prop="isEnable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isEnable"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否默认" align="center" prop="isDefault" /> -->
      <af-table-column label="批次条码规则" align="center" prop="ruleContent" />
      <el-table-column :label="$t('createUser')" align="center" prop="createBy" min-width="100"/>
      <el-table-column :label="$t('createTime')" align="center" prop="createTime" width="152">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('updateUser')" align="center" prop="updateBy" min-width="100"/>
      <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" width="152">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('operate')" align="center" class-name="small-padding fixed-width" width="125px" fixed='right'>
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:codeRule:edit']"
          >{{$t('edit')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:codeRule:remove']"
          >{{$t('delete')}}</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" style="max-height:70vh;overflow-y:auto;padding-right: 6px;">
        <el-form-item label="规则编号" prop="no">
          <el-input v-model="form.no" :disabled="form.id" placeholder="请输入规则编号" />
        </el-form-item>
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select style="width:100%;" v-model="form.ruleType" filterable placeholder="请选择规则类型">
            <el-option
              v-for="dict in ruleTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="isEnable" label-width='10px'>
            <el-checkbox v-model="form.isEnable" label="是否启用" name="isEnable" true-label='Y' false-label='N'></el-checkbox>
            <!-- <el-checkbox label="是否默认" name="isDefault" true-label='Y' false-label='N'></el-checkbox> -->
        </el-form-item>

        <div style="margin-bottom:20px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleElementAdd" v-hasPermi="['basic:codeRule:add']">新增元素</el-button>
            </el-col>
          </el-row>
          <el-table :data="form.wmsCodeRuleDetailList">
            <el-table-column label="属性" align="center" prop="property" width="150px">
              <template slot-scope="scope">
                <el-select v-model="scope.row.property" filterable placeholder="请选择规则属性">
                  <el-option v-for="dict in dict.type.barcode_rule_element" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="参数" align="center" prop="param" >
              <template slot="header" slot-scope="scope">
                参数
                <el-tooltip content="请输入参数对应的格式或位数" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip>
              </template>
              <template slot-scope="scope">
                <div class="flex-row">
                  <el-input v-model="scope.row.param" type="text" placeholder="请输入参数" />
                  <!-- <el-tooltip content="请输入参数对应的格式或位数" placement="top">
                  <i class="el-icon-question"></i>
                  </el-tooltip> -->
                </div>
              </template>
            </el-table-column>

            <el-table-column label="排序" align="center" prop="sort" width="120px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.sort" controls-position="right" :min="1" style="width:100px" />
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80px">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleElementDelete(scope.$index)" v-hasPermi="['basic:codeRule:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- <el-form-item label="规则顺序" prop="postSort">
          <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="规则状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="前缀" prop="prefix">
          <el-input v-model="form.prefix" placeholder="请输入前缀" />
        </el-form-item>
        <el-form-item label="分隔符" prop="breakCode">
          <el-select v-model="form.breakCode" filterable clearable placeholder="请选择分隔符">
            <el-option v-for="dict in breakCodeData" :key="dict" :label="dict" :value="dict"></el-option>
          </el-select>
          <!-- <el-input v-model="form.breakCode" placeholder="请输入分隔符" /> -->
        </el-form-item>
        <el-form-item label="条码规则" prop="ruleContent">
          <span>{{calcRule()}}</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('sure')}}</el-button>
        <el-button @click="cancel">{{$t('cancel')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, getDetail, del, add, update } from "@/api/basic/codeRule";

export default {
  name: "codeRule",
  dicts: ['sys_normal_disable','barcode_rule_element','sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 规则表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: undefined,
        // ruleName: undefined,
        // status: undefined
      },
      // 表单参数
      form: {
        wmsCodeRuleDetailList:[],
      },
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        ruleType: [
          { required: true, message: "规则类型不能为空", trigger: "blur" }
        ]
      },
      ruleTypeList:[{value:'BARCODE',label:'条码'}],
      // ruleTypeList:[{value:'BATCH',label:'批次号'},{value:'BARCODE',label:'条码'}],
      breakCodeData:['-','|']
    };
  },
  created() {
    this.getList();
  },
  methods: {
    calcRule(){
      let rule = [];
      if(this.form.prefix){
        rule.push(this.form.prefix);
      }
      let wmsCodeRuleDetailList = [...this.form.wmsCodeRuleDetailList]
      if(wmsCodeRuleDetailList.length){
        wmsCodeRuleDetailList.sort(this.sortFunc).forEach(item => {
          if(item.property){
            let property = this.dict.type.barcode_rule_element.find(element=>element.value == item.property)
            rule.push('['+property.label+']')
          }
        });
      }
      this.form.ruleContent = rule.join(this.form.breakCode||'')
      return this.form.ruleContent
    },
    sortFunc(a,b){
      let sort = a.sort-b.sort
      if(!b.sort){
        sort = -1
      }
      if(!a.sort){
        sort = 1
      }
      return sort;
    },
    // 规则元素列表 新增
    handleElementAdd(){
      this.form.wmsCodeRuleDetailList.push({property:'',param:'',sort:1})
    },
    // 规则元素列表 删除
    handleElementDelete(index){
      this.form.wmsCodeRuleDetailList.splice(index,1)

    },
    /** 查询规则列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        no: undefined,
        ruleName: undefined,
        ruleType: undefined,
        isEnable: 'N',
        isDefault: 'N',
        wmsCodeRuleDetailList: [],
        prefix:undefined,
        breakCode:undefined,
        ruleContent:undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加条码规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDetail(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改条码规则";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          add(this.form).then(response => {
            if (this.form.id != undefined) {
              this.$modal.msgSuccess(this.$t('editSuc'));
            }else{
              this.$modal.msgSuccess(this.$t('addSuc'));
            }
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
        return del(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('deleteSuc'));
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('system/post/export', {
    //     ...this.queryParams
    //   }, `post_${new Date().getTime()}.xlsx`)
    // }
  }
};
</script>
